<template>
	<view>
		<view class="box">
			<view class="example">
							<!-- 基础用法，不包含校验规则 -->
							<uni-forms ref="addressInfo" :rules="rules" :modelValue="addressInfo">
								<uni-forms-item label="收货人" name="userName"required>
									<uni-easyinput v-model="addressInfo.userName" placeholder="请输入收货人" />
								</uni-forms-item>
								<uni-forms-item label="地址" name="address" required>
									<uni-easyinput v-model="addressInfo.address" placeholder="请输入地址" />
								</uni-forms-item>
								<uni-forms-item label="手机号" name= "phone" required>
									<uni-easyinput v-model="addressInfo.phone" placeholder="请输入手机号" />
								</uni-forms-item>
							</uni-forms>
							<button type="primary" @click="submit('addressInfo')">确认</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		onLoad(option){
			if(option.addressId){
				this.addressId = option.addressId
				this.load()
			}
		},
		data() {
			return {
				user:uni.getStorageSync('xm-user'),
				addressId:'',
				addressInfo:{},
				rules: {
									userName: {
										rules: [{
											required: true,
											errorMessage: '姓名不能为空'
										}]
									},
									address: {
										rules: [{
											required: true,
											errorMessage: '地址不能为空'
										}]
									},
									phone: {
										rules:[{
											required: true,
											errorMessage: '手机号不能为空'
										},
										{
											format: 'number',
											errorMessage: '手机号只能输入数字'
										}
										]
									}
								},
			
			}
		},
		methods: {
			load(){
				this.$request.get('/address/selectById/'+this.addressId).then(res =>{
					this.addressInfo = res.data 
				})
			},
			save(){
				if(this.addressInfo.id){
					//修改
					this.$request.post('/address/updateById/',this.addressInfo).then(res =>{
						if(res.code == 200){
							uni.showToast({
								icon:'success',
								 title: res.msg
							})
						
						}
					})
				}else{
					//添加
					this.addressInfo.userId = this.user.id
					this.$request.post('/address/add/',this.addressInfo).then(res =>{
						if(res.code == 200){
							uni.showToast({
								icon:'success',
								 title: res.msg
							})
						
						}
					})
				}
				uni.navigateBack()
					
	
			},
			submit(ref) {
							this.$refs[ref].validate().then(res => {
								this.save()
							}).catch(err => {
								console.log('err', err);
							})
						},
			
		
		}
	}
</script>

<style>
.example {
		padding: 15px;
		background-color: #fff;
	}
</style>
